/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.application.commands;

import com.nanosn.coffeemaker.databaseproject.persistence.DatabaseJDBCConfiguration;
import com.nanosn.coffeemaker.java.ProjectClassLoader;
import com.nanosn.util.parsers.commandline.Command;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.openjpa.jdbc.meta.MappingTool;
import org.apache.openjpa.jdbc.schema.SchemaTool;

/**
 *
 * @author selkhateeb
 */
public class SyncDB implements Command {

    @Override
    public void run(String[] args) throws Exception {

        // Validate Models
        new Validate().run(new String[]{});

        // TODO: Assuming they are already loadded in the classpath!


        //get all model files in installed apps
        ProjectClassLoader pcl = ProjectClassLoader.getInstance();

        Class<?>[] classes = pcl.getModelClasses();
        List<String> classNames = new ArrayList();

        for (Class<?> clazz : classes) {
            classNames.add(clazz.getName());
        }

        //sync 'em -> run mapping tool
        doMappingTool(classNames.toArray(new String[classNames.size()]));

    }

    @Override
    public String getHelp() {
        return "Updates the database with the models";

    }

    public void doMappingTool(String[] classList) throws Exception {

        DatabaseJDBCConfiguration conf = new DatabaseJDBCConfiguration();

        ClassLoader loader = ProjectClassLoader.getInstance();
        Writer w = new OutputStreamWriter(System.out);

        MappingTool.Flags flags = new MappingTool.Flags();
        flags.action = MappingTool.ACTION_REFRESH;
        flags.schemaAction = SchemaTool.ACTION_REFRESH;
////        flags.sqlWriter = w;
//        flags.ignoreErrors = false;
//        flags.readSchema = false;
//        flags.dropTables = false;
//        flags.openjpaTables = false;
//        flags.dropSequences = false;
//        flags.sequences = false; // true;
//        flags.primaryKeys = false;
//        flags.foreignKeys = false;
//        flags.indexes = false;

        MappingTool.run(conf, classList, flags, loader);
        w.flush();
        w.close();

        /* TODO: Find another way to delete the derby.log file to keep things
         *      clean
         *      .. but for now ..
         */
//        File derby_log = new File("derby.log");
//        if (derby_log.exists()) {
//            derby_log.delete();
//        }
    }
}
